﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace Battle
{
    public abstract class EnemyBase : MonoBehaviour, ICanHitObj,IBuffMgr
    {
        public int GoldReward { get; protected set; } = 1;
        public int ScienceReward { get; protected set; } = 1;
        public float Hp { get; protected set; } = 1;
        public bool IsDeath { get; protected set; } = false;

        public Vector3 Pos => transform != null ? transform.position : Vector3.zero;

        public EnemyMoveBase MoveComponent { get; protected set; }

        protected IBuffMgr buffMgr;

        protected virtual void Awake()
        {
            buffMgr = new BuffMgr_Normal(this);

            EnemyMgr.Ins.LogIn(this);
        }
        protected virtual void OnDestroy()
        {
            (buffMgr as BuffMgr_Normal)?.DestorySelf();

            EnemyMgr.Ins.LogOut(this);
        }

        public virtual void Death()
        {
            if (IsDeath) return;

            IsDeath = true;
            EnemyMgr.Ins.OnEnemyDeath(this);
            Destroy(this.gameObject);
        }

        public virtual void OnHit(ST_HitActionData hitActionData)
        {
            if (IsDeath) return;

            Hp -= hitActionData.fAtk;
            if (Hp <= 0)
                Death();
            else if (hitActionData.nRepelNum != 0)
                MoveComponent?.OnRepel(Hp, hitActionData.nRepelNum, hitActionData.vRepelDir.normalized);
        }

        #region buffMgr 解释器写法

        public string AddBuff(ST_ObjBuffData buffData)
        {
            return buffMgr.AddBuff(buffData);
        }

        public ST_ObjBuffData[] GetBuffDatas(string name)
        {
            return buffMgr.GetBuffDatas(name);
        }

        public void RemoveBuff(string guid)
        {
            buffMgr.RemoveBuff(guid);
        }

        public void RemoveAllBuff(Func<ST_ObjBuffData, bool> check)
        {
            buffMgr.RemoveAllBuff(check);
        }
        public void ChangeBuff(ST_ObjBuffData buffData)
        {
            buffMgr.ChangeBuff(buffData);
        }

        public T GetObj<T>() where T : class
        {
            Type type = typeof(T);

            if (type.IsAssignableFrom(GetType()) || typeof(ICanHitObj) == type) return this as T;
            if (MoveComponent != null && type.IsAssignableFrom(MoveComponent.GetType())) return MoveComponent as T;
            if (type == typeof(Transform)) return transform as T;
            if (typeof(Component).IsAssignableFrom(type)) return GetComponentInChildren<T>();

            return buffMgr.GetObj<T>();
        }
        #endregion
    }
}